{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "/home/husein/.local/lib/python3.6/site-packages/tensorflow/python/framework/dtypes.py:516: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'.\n",
      "  _np_qint8 = np.dtype([(\"qint8\", np.int8, 1)])\n",
      "/home/husein/.local/lib/python3.6/site-packages/tensorflow/python/framework/dtypes.py:517: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'.\n",
      "  _np_quint8 = np.dtype([(\"quint8\", np.uint8, 1)])\n",
      "/home/husein/.local/lib/python3.6/site-packages/tensorflow/python/framework/dtypes.py:518: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'.\n",
      "  _np_qint16 = np.dtype([(\"qint16\", np.int16, 1)])\n",
      "/home/husein/.local/lib/python3.6/site-packages/tensorflow/python/framework/dtypes.py:519: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'.\n",
      "  _np_quint16 = np.dtype([(\"quint16\", np.uint16, 1)])\n",
      "/home/husein/.local/lib/python3.6/site-packages/tensorflow/python/framework/dtypes.py:520: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'.\n",
      "  _np_qint32 = np.dtype([(\"qint32\", np.int32, 1)])\n",
      "/home/husein/.local/lib/python3.6/site-packages/tensorflow/python/framework/dtypes.py:525: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'.\n",
      "  np_resource = np.dtype([(\"resource\", np.ubyte, 1)])\n",
      "/home/husein/.local/lib/python3.6/site-packages/tensorboard/compat/tensorflow_stub/dtypes.py:541: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'.\n",
      "  _np_qint8 = np.dtype([(\"qint8\", np.int8, 1)])\n",
      "/home/husein/.local/lib/python3.6/site-packages/tensorboard/compat/tensorflow_stub/dtypes.py:542: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'.\n",
      "  _np_quint8 = np.dtype([(\"quint8\", np.uint8, 1)])\n",
      "/home/husein/.local/lib/python3.6/site-packages/tensorboard/compat/tensorflow_stub/dtypes.py:543: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'.\n",
      "  _np_qint16 = np.dtype([(\"qint16\", np.int16, 1)])\n",
      "/home/husein/.local/lib/python3.6/site-packages/tensorboard/compat/tensorflow_stub/dtypes.py:544: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'.\n",
      "  _np_quint16 = np.dtype([(\"quint16\", np.uint16, 1)])\n",
      "/home/husein/.local/lib/python3.6/site-packages/tensorboard/compat/tensorflow_stub/dtypes.py:545: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'.\n",
      "  _np_qint32 = np.dtype([(\"qint32\", np.int32, 1)])\n",
      "/home/husein/.local/lib/python3.6/site-packages/tensorboard/compat/tensorflow_stub/dtypes.py:550: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'.\n",
      "  np_resource = np.dtype([(\"resource\", np.ubyte, 1)])\n"
     ]
    }
   ],
   "source": [
    "import tensorflow as tf\n",
    "import numpy as np\n",
    "import pickle"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "dict_keys(['train_texts', 'test_texts', 'train_clss', 'test_clss', 'train_labels', 'test_labels'])"
      ]
     },
     "execution_count": 2,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "with open('dataset.pkl', 'rb') as fopen:\n",
    "    dataset = pickle.load(fopen)\n",
    "dataset.keys()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "73967"
      ]
     },
     "execution_count": 3,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "len(dataset['train_texts'])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [],
   "source": [
    "with open('dictionary.pkl', 'rb') as fopen:\n",
    "    dictionary = pickle.load(fopen)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [],
   "source": [
    "rev_dictionary = dictionary['rev_dictionary']\n",
    "dictionary = dictionary['dictionary']"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {},
   "outputs": [],
   "source": [
    "def ln(inputs, epsilon = 1e-8, scope=\"ln\"):\n",
    "    with tf.variable_scope(scope, reuse=tf.AUTO_REUSE):\n",
    "        inputs_shape = inputs.get_shape()\n",
    "        params_shape = inputs_shape[-1:]\n",
    "    \n",
    "        mean, variance = tf.nn.moments(inputs, [-1], keep_dims=True)\n",
    "        beta= tf.get_variable(\"beta\", params_shape, initializer=tf.zeros_initializer())\n",
    "        gamma = tf.get_variable(\"gamma\", params_shape, initializer=tf.ones_initializer())\n",
    "        normalized = (inputs - mean) / ( (variance + epsilon) ** (.5) )\n",
    "        outputs = gamma * normalized + beta\n",
    "        \n",
    "    return outputs\n",
    "\n",
    "def scaled_dot_product_attention(Q, K, V,\n",
    "                                 causality=False, dropout_rate=0.,\n",
    "                                 training=True,\n",
    "                                 scope=\"scaled_dot_product_attention\"):\n",
    "    with tf.variable_scope(scope, reuse=tf.AUTO_REUSE):\n",
    "        d_k = Q.get_shape().as_list()[-1]\n",
    "\n",
    "        outputs = tf.matmul(Q, tf.transpose(K, [0, 2, 1]))  # (N, T_q, T_k)\n",
    "        outputs /= d_k ** 0.5\n",
    "        outputs = mask(outputs, Q, K, type=\"key\")\n",
    "        if causality:\n",
    "            outputs = mask(outputs, type=\"future\")\n",
    "        outputs = tf.nn.softmax(outputs)\n",
    "        attention = tf.transpose(outputs, [0, 2, 1])\n",
    "        #tf.summary.image(\"attention\", tf.expand_dims(attention[:1], -1))\n",
    "        outputs = mask(outputs, Q, K, type=\"query\")\n",
    "        outputs = tf.layers.dropout(outputs, rate=dropout_rate, training=training)\n",
    "        outputs = tf.matmul(outputs, V)\n",
    "    return outputs\n",
    "\n",
    "def mask(inputs, queries=None, keys=None, type=None):\n",
    "    padding_num = -2 ** 32 + 1\n",
    "    if type in (\"k\", \"key\", \"keys\"):\n",
    "        masks = tf.sign(tf.reduce_sum(tf.abs(keys), axis=-1))  # (N, T_k)\n",
    "        masks = tf.expand_dims(masks, 1) # (N, 1, T_k)\n",
    "        masks = tf.tile(masks, [1, tf.shape(queries)[1], 1])  # (N, T_q, T_k)\n",
    "        paddings = tf.ones_like(inputs) * padding_num\n",
    "        outputs = tf.where(tf.equal(masks, 0), paddings, inputs)  # (N, T_q, T_k)\n",
    "    elif type in (\"q\", \"query\", \"queries\"):\n",
    "        masks = tf.sign(tf.reduce_sum(tf.abs(queries), axis=-1))  # (N, T_q)\n",
    "        masks = tf.expand_dims(masks, -1)  # (N, T_q, 1)\n",
    "        masks = tf.tile(masks, [1, 1, tf.shape(keys)[1]])  # (N, T_q, T_k)\n",
    "        outputs = inputs*masks\n",
    "    elif type in (\"f\", \"future\", \"right\"):\n",
    "        diag_vals = tf.ones_like(inputs[0, :, :])  # (T_q, T_k)\n",
    "        tril = tf.linalg.LinearOperatorLowerTriangular(diag_vals).to_dense()  # (T_q, T_k)\n",
    "        masks = tf.tile(tf.expand_dims(tril, 0), [tf.shape(inputs)[0], 1, 1])  # (N, T_q, T_k)\n",
    "        paddings = tf.ones_like(masks) * padding_num\n",
    "        outputs = tf.where(tf.equal(masks, 0), paddings, inputs)\n",
    "    else:\n",
    "        print(\"Check if you entered type correctly!\")\n",
    "\n",
    "\n",
    "    return outputs\n",
    "\n",
    "def multihead_attention(queries, keys, values,\n",
    "                        num_heads=8, \n",
    "                        dropout_rate=0,\n",
    "                        training=True,\n",
    "                        causality=False,\n",
    "                        scope=\"multihead_attention\"):\n",
    "    d_model = queries.get_shape().as_list()[-1]\n",
    "    with tf.variable_scope(scope, reuse=tf.AUTO_REUSE):\n",
    "        # Linear projections\n",
    "        Q = tf.layers.dense(queries, d_model, use_bias=False) # (N, T_q, d_model)\n",
    "        K = tf.layers.dense(keys, d_model, use_bias=False) # (N, T_k, d_model)\n",
    "        V = tf.layers.dense(values, d_model, use_bias=False) # (N, T_k, d_model)\n",
    "        \n",
    "        Q_ = tf.concat(tf.split(Q, num_heads, axis=2), axis=0) # (h*N, T_q, d_model/h)\n",
    "        K_ = tf.concat(tf.split(K, num_heads, axis=2), axis=0) # (h*N, T_k, d_model/h)\n",
    "        V_ = tf.concat(tf.split(V, num_heads, axis=2), axis=0) # (h*N, T_k, d_model/h)\n",
    "\n",
    "        outputs = scaled_dot_product_attention(Q_, K_, V_, causality, dropout_rate, training)\n",
    "        outputs = tf.concat(tf.split(outputs, num_heads, axis=0), axis=2 ) # (N, T_q, d_model)\n",
    "        outputs += queries\n",
    "        outputs = ln(outputs)\n",
    " \n",
    "    return outputs\n",
    "\n",
    "def ff(inputs, num_units, scope=\"positionwise_feedforward\"):\n",
    "    with tf.variable_scope(scope, reuse=tf.AUTO_REUSE):\n",
    "        outputs = tf.layers.dense(inputs, num_units[0], activation=tf.nn.relu)\n",
    "        outputs = tf.layers.dense(outputs, num_units[1])\n",
    "        outputs += inputs\n",
    "        outputs = ln(outputs)\n",
    "    \n",
    "    return outputs\n",
    "\n",
    "def label_smoothing(inputs, epsilon=0.1):\n",
    "    V = inputs.get_shape().as_list()[-1] # number of channels\n",
    "    return ((1-epsilon) * inputs) + (epsilon / V)\n",
    "\n",
    "def sinusoidal_position_encoding(inputs, mask, repr_dim):\n",
    "    T = tf.shape(inputs)[1]\n",
    "    pos = tf.reshape(tf.range(0.0, tf.to_float(T), dtype=tf.float32), [-1, 1])\n",
    "    i = np.arange(0, repr_dim, 2, np.float32)\n",
    "    denom = np.reshape(np.power(10000.0, i / repr_dim), [1, -1])\n",
    "    enc = tf.expand_dims(tf.concat([tf.sin(pos / denom), tf.cos(pos / denom)], 1), 0)\n",
    "    return tf.tile(enc, [tf.shape(inputs)[0], 1, 1]) * tf.expand_dims(tf.to_float(mask), -1)\n",
    "\n",
    "class Model:\n",
    "    def __init__(self, size_layer, embedded_size,\n",
    "                 dict_size, learning_rate,\n",
    "                 num_blocks = 4, num_heads = 8, ratio_hidden = 2):\n",
    "        \n",
    "        def cells(reuse=False):\n",
    "            return tf.nn.rnn_cell.LSTMCell(size_layer,initializer=tf.orthogonal_initializer(),reuse=reuse)\n",
    "        \n",
    "        self.X = tf.placeholder(tf.int32, [None, None])\n",
    "        self.Y = tf.placeholder(tf.float32, [None, None])\n",
    "        self.mask = tf.placeholder(tf.int32, [None, None])\n",
    "        self.clss = tf.placeholder(tf.int32, [None, None])\n",
    "        mask = tf.cast(self.mask, tf.float32)\n",
    "        encoder_embeddings = tf.Variable(tf.random_uniform([dict_size, embedded_size], -1, 1))\n",
    "        encoder_embedded = tf.nn.embedding_lookup(encoder_embeddings, self.X)\n",
    "        en_masks = tf.sign(self.X)\n",
    "        encoder_embedded += sinusoidal_position_encoding(self.X, en_masks, size_layer)\n",
    "        enc = encoder_embedded\n",
    "        \n",
    "        for i in range(num_blocks):\n",
    "            with tf.variable_scope('encoder_self_attn_%d'%i,reuse=False):\n",
    "                enc = multihead_attention(queries=enc,\n",
    "                                          keys=enc,\n",
    "                                          values=enc,\n",
    "                                          num_heads=num_heads,\n",
    "                                          causality=False)\n",
    "                enc = ff(enc, num_units=[size_layer * ratio_hidden, size_layer])\n",
    "                        \n",
    "        outputs = tf.gather(enc, self.clss, axis = 1, batch_dims = 1)\n",
    "        self.logits = tf.layers.dense(outputs, 1)\n",
    "        self.logits = tf.squeeze(self.logits, axis=-1)\n",
    "        self.logits = self.logits * mask\n",
    "        crossent = tf.nn.sigmoid_cross_entropy_with_logits(logits=self.logits, labels=self.Y)\n",
    "        crossent = crossent * mask\n",
    "        crossent = tf.reduce_sum(crossent)\n",
    "        total_size = tf.reduce_sum(mask)\n",
    "        self.cost = tf.div_no_nan(crossent, total_size)\n",
    "        \n",
    "        self.optimizer = tf.train.AdamOptimizer(learning_rate = learning_rate).minimize(self.cost)\n",
    "        \n",
    "        l = tf.round(tf.sigmoid(self.logits))\n",
    "        self.accuracy = tf.reduce_mean(tf.cast(tf.boolean_mask(l, tf.equal(self.Y, 1)), tf.float32))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {},
   "outputs": [],
   "source": [
    "size_layer = 256\n",
    "embedded_size = 256\n",
    "learning_rate = 1e-3"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "WARNING:tensorflow:From <ipython-input-6-385ed069ad9c>:98: to_float (from tensorflow.python.ops.math_ops) is deprecated and will be removed in a future version.\n",
      "Instructions for updating:\n",
      "Use `tf.cast` instead.\n",
      "WARNING:tensorflow:From <ipython-input-6-385ed069ad9c>:68: dense (from tensorflow.python.layers.core) is deprecated and will be removed in a future version.\n",
      "Instructions for updating:\n",
      "Use keras.layers.dense instead.\n",
      "WARNING:tensorflow:From /home/husein/.local/lib/python3.6/site-packages/tensorflow/python/ops/init_ops.py:1251: calling VarianceScaling.__init__ (from tensorflow.python.ops.init_ops) with dtype is deprecated and will be removed in a future version.\n",
      "Instructions for updating:\n",
      "Call initializer instance with the dtype argument instead of passing it to the constructor\n",
      "WARNING:tensorflow:From <ipython-input-6-385ed069ad9c>:41: add_dispatch_support.<locals>.wrapper (from tensorflow.python.ops.array_ops) is deprecated and will be removed in a future version.\n",
      "Instructions for updating:\n",
      "Use tf.where in 2.0, which has the same broadcast rule as np.where\n",
      "WARNING:tensorflow:From <ipython-input-6-385ed069ad9c>:30: dropout (from tensorflow.python.layers.core) is deprecated and will be removed in a future version.\n",
      "Instructions for updating:\n",
      "Use keras.layers.dropout instead.\n"
     ]
    }
   ],
   "source": [
    "tf.reset_default_graph()\n",
    "sess = tf.InteractiveSession()\n",
    "model = Model(size_layer,embedded_size,len(dictionary),learning_rate)\n",
    "sess.run(tf.global_variables_initializer())"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "metadata": {},
   "outputs": [],
   "source": [
    "UNK = 3\n",
    "\n",
    "def str_idx(corpus, dic):\n",
    "    X = []\n",
    "    for i in corpus:\n",
    "        ints = []\n",
    "        for k in i.split():\n",
    "            ints.append(dic.get(k,UNK))\n",
    "        X.append(ints)\n",
    "    return X\n",
    "\n",
    "def pad_sentence_batch(sentence_batch, pad_int):\n",
    "    padded_seqs = []\n",
    "    seq_lens = []\n",
    "    max_sentence_len = max([len(sentence) for sentence in sentence_batch])\n",
    "    for sentence in sentence_batch:\n",
    "        padded_seqs.append(sentence + [pad_int] * (max_sentence_len - len(sentence)))\n",
    "        seq_lens.append(len(sentence))\n",
    "    return padded_seqs, seq_lens"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "metadata": {},
   "outputs": [],
   "source": [
    "train_X = str_idx(dataset['train_texts'], dictionary)\n",
    "test_X = str_idx(dataset['test_texts'], dictionary)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "metadata": {},
   "outputs": [],
   "source": [
    "train_clss = dataset['train_clss']\n",
    "test_clss = dataset['test_clss']\n",
    "train_Y = dataset['train_labels']\n",
    "test_Y = dataset['test_labels']"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "(1.0, 1.4390177)"
      ]
     },
     "execution_count": 12,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "batch_x, _ = pad_sentence_batch(train_X[:64], 0)\n",
    "batch_y, _ = pad_sentence_batch(train_Y[:64], 0)\n",
    "batch_clss, _ = pad_sentence_batch(train_clss[:64], -1)\n",
    "batch_clss = np.array(batch_clss)\n",
    "batch_mask = 1 - (batch_clss == -1)\n",
    "batch_clss[batch_clss == -1] = 0\n",
    "\n",
    "feed = {model.X: batch_x,\n",
    "        model.Y: batch_y,\n",
    "        model.mask: batch_mask,\n",
    "        model.clss: batch_clss}\n",
    "acc, loss, _ = sess.run([model.accuracy, model.cost,model.optimizer], feed_dict = feed)\n",
    "acc, loss"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1156/1156 [06:35<00:00,  2.92it/s, accuracy=0.0167, cost=0.376] \n",
      "minibatch loop: 100%|██████████| 289/289 [00:37<00:00,  7.65it/s, accuracy=0.00641, cost=0.397]\n",
      "minibatch loop:   0%|          | 0/1156 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 1, training avg loss 0.387910, training avg acc 0.008459\n",
      "epoch 1, testing avg loss 0.378677, testing avg acc 0.002847\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1156/1156 [06:35<00:00,  2.92it/s, accuracy=0.0167, cost=0.37]  \n",
      "minibatch loop: 100%|██████████| 289/289 [00:37<00:00,  7.67it/s, accuracy=0.00641, cost=0.393]\n",
      "minibatch loop:   0%|          | 0/1156 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 2, training avg loss 0.374503, training avg acc 0.029881\n",
      "epoch 2, testing avg loss 0.375109, testing avg acc 0.003962\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1156/1156 [06:35<00:00,  2.92it/s, accuracy=0.1, cost=0.349]   \n",
      "minibatch loop: 100%|██████████| 289/289 [00:37<00:00,  7.68it/s, accuracy=0.0321, cost=0.397]\n",
      "minibatch loop:   0%|          | 0/1156 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 3, training avg loss 0.365837, training avg acc 0.061967\n",
      "epoch 3, testing avg loss 0.378205, testing avg acc 0.052813\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1156/1156 [06:35<00:00,  2.92it/s, accuracy=0.225, cost=0.324] \n",
      "minibatch loop: 100%|██████████| 289/289 [00:37<00:00,  7.67it/s, accuracy=0.0705, cost=0.406]\n",
      "minibatch loop:   0%|          | 0/1156 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 4, training avg loss 0.351095, training avg acc 0.128159\n",
      "epoch 4, testing avg loss 0.392094, testing avg acc 0.101840\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1156/1156 [06:35<00:00,  2.92it/s, accuracy=0.358, cost=0.299]\n",
      "minibatch loop: 100%|██████████| 289/289 [00:37<00:00,  7.67it/s, accuracy=0.154, cost=0.426]\n",
      "minibatch loop:   0%|          | 0/1156 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 5, training avg loss 0.329346, training avg acc 0.222128\n",
      "epoch 5, testing avg loss 0.413041, testing avg acc 0.174466\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1156/1156 [06:35<00:00,  2.92it/s, accuracy=0.433, cost=0.262]\n",
      "minibatch loop: 100%|██████████| 289/289 [00:37<00:00,  7.67it/s, accuracy=0.135, cost=0.455]\n",
      "minibatch loop:   0%|          | 0/1156 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 6, training avg loss 0.305964, training avg acc 0.309037\n",
      "epoch 6, testing avg loss 0.436760, testing avg acc 0.183248\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1156/1156 [06:35<00:00,  2.92it/s, accuracy=0.533, cost=0.219]\n",
      "minibatch loop: 100%|██████████| 289/289 [00:37<00:00,  7.65it/s, accuracy=0.141, cost=0.492]\n",
      "minibatch loop:   0%|          | 0/1156 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 7, training avg loss 0.281421, training avg acc 0.392515\n",
      "epoch 7, testing avg loss 0.472197, testing avg acc 0.184607\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1156/1156 [06:35<00:00,  2.92it/s, accuracy=0.7, cost=0.186]  \n",
      "minibatch loop: 100%|██████████| 289/289 [00:37<00:00,  7.65it/s, accuracy=0.173, cost=0.543]\n",
      "minibatch loop:   0%|          | 0/1156 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 8, training avg loss 0.252382, training avg acc 0.477697\n",
      "epoch 8, testing avg loss 0.522769, testing avg acc 0.221310\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1156/1156 [06:43<00:00,  2.87it/s, accuracy=0.742, cost=0.142]\n",
      "minibatch loop: 100%|██████████| 289/289 [00:37<00:00,  7.65it/s, accuracy=0.173, cost=0.641]\n",
      "minibatch loop:   0%|          | 0/1156 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 9, training avg loss 0.225019, training avg acc 0.549972\n",
      "epoch 9, testing avg loss 0.597408, testing avg acc 0.246061\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1156/1156 [06:42<00:00,  2.87it/s, accuracy=0.775, cost=0.121]\n",
      "minibatch loop: 100%|██████████| 289/289 [00:38<00:00,  7.60it/s, accuracy=0.154, cost=0.644]\n",
      "minibatch loop:   0%|          | 0/1156 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 10, training avg loss 0.203076, training avg acc 0.606897\n",
      "epoch 10, testing avg loss 0.594545, testing avg acc 0.227027\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1156/1156 [06:37<00:00,  2.91it/s, accuracy=0.792, cost=0.102]\n",
      "minibatch loop: 100%|██████████| 289/289 [00:37<00:00,  7.61it/s, accuracy=0.179, cost=0.728]\n",
      "minibatch loop:   0%|          | 0/1156 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 11, training avg loss 0.189718, training avg acc 0.639519\n",
      "epoch 11, testing avg loss 0.670387, testing avg acc 0.249209\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1156/1156 [06:37<00:00,  2.91it/s, accuracy=0.883, cost=0.0795]\n",
      "minibatch loop: 100%|██████████| 289/289 [00:37<00:00,  7.61it/s, accuracy=0.167, cost=0.775]\n",
      "minibatch loop:   0%|          | 0/1156 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 12, training avg loss 0.168331, training avg acc 0.688725\n",
      "epoch 12, testing avg loss 0.721593, testing avg acc 0.229948\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1156/1156 [06:35<00:00,  2.92it/s, accuracy=0.892, cost=0.0754]\n",
      "minibatch loop: 100%|██████████| 289/289 [00:37<00:00,  7.65it/s, accuracy=0.167, cost=0.728]\n",
      "minibatch loop:   0%|          | 0/1156 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 13, training avg loss 0.147944, training avg acc 0.734141\n",
      "epoch 13, testing avg loss 0.681439, testing avg acc 0.234368\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1156/1156 [06:35<00:00,  2.92it/s, accuracy=0.9, cost=0.0825]  \n",
      "minibatch loop: 100%|██████████| 289/289 [00:37<00:00,  7.64it/s, accuracy=0.192, cost=0.824]\n",
      "minibatch loop:   0%|          | 0/1156 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 14, training avg loss 0.135995, training avg acc 0.758445\n",
      "epoch 14, testing avg loss 0.749728, testing avg acc 0.255525\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1156/1156 [06:35<00:00,  2.92it/s, accuracy=0.958, cost=0.0592]\n",
      "minibatch loop: 100%|██████████| 289/289 [00:37<00:00,  7.64it/s, accuracy=0.205, cost=0.873]\n",
      "minibatch loop:   0%|          | 0/1156 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 15, training avg loss 0.127149, training avg acc 0.778638\n",
      "epoch 15, testing avg loss 0.811870, testing avg acc 0.269463\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1156/1156 [06:35<00:00,  2.92it/s, accuracy=0.9, cost=0.0623]  \n",
      "minibatch loop: 100%|██████████| 289/289 [00:37<00:00,  7.66it/s, accuracy=0.186, cost=0.957]\n",
      "minibatch loop:   0%|          | 0/1156 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 16, training avg loss 0.110549, training avg acc 0.812205\n",
      "epoch 16, testing avg loss 0.862229, testing avg acc 0.248714\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1156/1156 [06:35<00:00,  2.92it/s, accuracy=0.875, cost=0.0698]\n",
      "minibatch loop: 100%|██████████| 289/289 [00:37<00:00,  7.64it/s, accuracy=0.212, cost=0.879]\n",
      "minibatch loop:   0%|          | 0/1156 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 17, training avg loss 0.099921, training avg acc 0.834709\n",
      "epoch 17, testing avg loss 0.792213, testing avg acc 0.235911\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1156/1156 [06:35<00:00,  2.92it/s, accuracy=0.933, cost=0.0742]\n",
      "minibatch loop: 100%|██████████| 289/289 [00:37<00:00,  7.65it/s, accuracy=0.205, cost=0.793]\n",
      "minibatch loop:   0%|          | 0/1156 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 18, training avg loss 0.099067, training avg acc 0.837627\n",
      "epoch 18, testing avg loss 0.752785, testing avg acc 0.243941\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1156/1156 [06:35<00:00,  2.92it/s, accuracy=0.933, cost=0.0539]\n",
      "minibatch loop: 100%|██████████| 289/289 [00:37<00:00,  7.65it/s, accuracy=0.205, cost=0.932]\n",
      "minibatch loop:   0%|          | 0/1156 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 19, training avg loss 0.087893, training avg acc 0.859114\n",
      "epoch 19, testing avg loss 0.854014, testing avg acc 0.258605\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1156/1156 [06:35<00:00,  2.92it/s, accuracy=0.933, cost=0.0515]\n",
      "minibatch loop: 100%|██████████| 289/289 [00:37<00:00,  7.65it/s, accuracy=0.179, cost=0.983]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 20, training avg loss 0.085529, training avg acc 0.863731\n",
      "epoch 20, testing avg loss 0.869859, testing avg acc 0.236150\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "\n"
     ]
    }
   ],
   "source": [
    "import tqdm\n",
    "\n",
    "batch_size = 64\n",
    "epoch = 20\n",
    "\n",
    "for e in range(epoch):\n",
    "    pbar = tqdm.tqdm(\n",
    "        range(0, len(train_X), batch_size), desc = 'minibatch loop')\n",
    "    train_loss, train_acc, test_loss, test_acc = [], [], [], []\n",
    "    for i in pbar:\n",
    "        index = min(i + batch_size, len(train_X))\n",
    "        batch_x, _ = pad_sentence_batch(train_X[i : index], 0)\n",
    "        batch_y, _ = pad_sentence_batch(train_Y[i : index], 0)\n",
    "        batch_clss, _ = pad_sentence_batch(train_clss[i : index], -1)\n",
    "        batch_clss = np.array(batch_clss)\n",
    "        batch_mask = 1 - (batch_clss == -1)\n",
    "        batch_clss[batch_clss == -1] = 0\n",
    "        feed = {model.X: batch_x,\n",
    "                model.Y: batch_y,\n",
    "                model.mask: batch_mask,\n",
    "                model.clss: batch_clss}\n",
    "        accuracy, loss, _ = sess.run([model.accuracy,model.cost,model.optimizer],\n",
    "                                    feed_dict = feed)\n",
    "        train_loss.append(loss)\n",
    "        train_acc.append(accuracy)\n",
    "        pbar.set_postfix(cost = loss, accuracy = accuracy)\n",
    "    \n",
    "    pbar = tqdm.tqdm(\n",
    "        range(0, len(test_X), batch_size), desc = 'minibatch loop')\n",
    "    for i in pbar:\n",
    "        index = min(i + batch_size, len(test_X))\n",
    "        batch_x, _ = pad_sentence_batch(test_X[i : index], 0)\n",
    "        batch_y, _ = pad_sentence_batch(test_Y[i : index], 0)\n",
    "        batch_clss, _ = pad_sentence_batch(test_clss[i : index], -1)\n",
    "        batch_clss = np.array(batch_clss)\n",
    "        batch_mask = 1 - (batch_clss == -1)\n",
    "        batch_clss[batch_clss == -1] = 0\n",
    "        feed = {model.X: batch_x,\n",
    "                model.Y: batch_y,\n",
    "                model.mask: batch_mask,\n",
    "                model.clss: batch_clss}\n",
    "        accuracy, loss = sess.run([model.accuracy,model.cost],\n",
    "                                    feed_dict = feed)\n",
    "\n",
    "        test_loss.append(loss)\n",
    "        test_acc.append(accuracy)\n",
    "        pbar.set_postfix(cost = loss, accuracy = accuracy)\n",
    "    \n",
    "    print('epoch %d, training avg loss %f, training avg acc %f'%(e+1,\n",
    "                                                                 np.mean(train_loss),np.mean(train_acc)))\n",
    "    print('epoch %d, testing avg loss %f, testing avg acc %f'%(e+1,\n",
    "                                                              np.mean(test_loss),np.mean(test_acc)))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 14,
   "metadata": {},
   "outputs": [],
   "source": [
    "from tensor2tensor.utils import rouge\n",
    "from tensorflow.keras.preprocessing import sequence\n",
    "\n",
    "def calculate_rouges(predicted, batch_y):\n",
    "    non = np.count_nonzero(batch_y, axis = 1)\n",
    "    o = []\n",
    "    for n in non:\n",
    "        o.append([True for _ in range(n)])\n",
    "    b = sequence.pad_sequences(o, dtype = np.bool, padding = 'post', value = False)\n",
    "    batch_y = np.array(batch_y)\n",
    "    rouges = []\n",
    "    for i in range(predicted.shape[0]):\n",
    "        a = batch_y[i][b[i]]\n",
    "        p = predicted[i][b[i]]\n",
    "        rouges.append(rouge.rouge_n([p], [a]))\n",
    "    return np.mean(rouges)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 15,
   "metadata": {},
   "outputs": [],
   "source": [
    "batch_x, _ = pad_sentence_batch(test_X[: 5], 0)\n",
    "batch_y, _ = pad_sentence_batch(test_Y[: 5], 0)\n",
    "batch_clss, _ = pad_sentence_batch(test_clss[: 5], -1)\n",
    "batch_clss = np.array(batch_clss)\n",
    "batch_y = np.array(batch_y)\n",
    "batch_x = np.array(batch_x)\n",
    "cp_batch_clss = batch_clss.copy()\n",
    "batch_mask = 1 - (batch_clss == -1)\n",
    "batch_clss[batch_clss == -1] = 0\n",
    "\n",
    "feed = {model.X: batch_x,\n",
    "        model.mask: batch_mask,\n",
    "        model.clss: batch_clss}\n",
    "predicted = sess.run(tf.round(tf.sigmoid(model.logits)), feed_dict = feed)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 16,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "0.19125411"
      ]
     },
     "execution_count": 16,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "from tensor2tensor.utils import rouge\n",
    "\n",
    "def calculate_rouge(predicted, batch_y, cp_batch_clss, batch_x):\n",
    "    f, y_, predicted_ = [], [], []\n",
    "    for i in range(len(cp_batch_clss)):\n",
    "        f.append(cp_batch_clss[i][cp_batch_clss[i] != -1])\n",
    "        y_.append(batch_y[i][cp_batch_clss[i] != -1])\n",
    "        predicted_.append(predicted[i][cp_batch_clss[i] != -1])\n",
    "    \n",
    "    actual, predict = [], []\n",
    "    for i in range(len(f)):\n",
    "        actual_, predict_ = [], []\n",
    "        for k in range(len(f[i])):\n",
    "            if k == (len(f[i]) - 1):\n",
    "                s = batch_x[i][f[i][k]:]\n",
    "                s = s[s != 0]\n",
    "            else:\n",
    "                s = batch_x[i][f[i][k]: f[i][k + 1]]\n",
    "            s = [w for w in s if w not in [0, 1, 2, 3, 5, 6, 7, 8]]\n",
    "            if y_[i][k]:\n",
    "                actual_.extend(s)\n",
    "            if predicted_[i][k]:\n",
    "                predict_.extend(s)\n",
    "        actual.append(actual_)\n",
    "        predict.append(predict_)\n",
    "    return rouge.rouge_n(predict, actual)\n",
    "\n",
    "calculate_rouge(predicted, batch_y, cp_batch_clss, batch_x)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 17,
   "metadata": {},
   "outputs": [],
   "source": [
    "from tqdm import tqdm as tqdm_base\n",
    "def tqdm(*args, **kwargs):\n",
    "    if hasattr(tqdm_base, '_instances'):\n",
    "        for instance in list(tqdm_base._instances):\n",
    "            tqdm_base._decr_instances(instance)\n",
    "    return tqdm_base(*args, **kwargs)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 18,
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 2312/2312 [14:40<00:00,  2.63it/s, rouge=0.211]\n"
     ]
    }
   ],
   "source": [
    "rouges = []\n",
    "\n",
    "pbar = tqdm(\n",
    "    range(0, len(test_X), 32), desc = 'minibatch loop')\n",
    "for i in pbar:\n",
    "    index = min(i + batch_size, len(test_X))\n",
    "    batch_x, _ = pad_sentence_batch(test_X[i: index], 0)\n",
    "    batch_y, _ = pad_sentence_batch(test_Y[i: index], 0)\n",
    "    batch_clss, _ = pad_sentence_batch(test_clss[i: index], -1)\n",
    "    batch_clss = np.array(batch_clss)\n",
    "    batch_y = np.array(batch_y)\n",
    "    batch_x = np.array(batch_x)\n",
    "    cp_batch_clss = batch_clss.copy()\n",
    "    batch_mask = 1 - (batch_clss == -1)\n",
    "    batch_clss[batch_clss == -1] = 0\n",
    "\n",
    "    feed = {model.X: batch_x,\n",
    "            model.mask: batch_mask,\n",
    "            model.clss: batch_clss}\n",
    "    predicted = sess.run(tf.round(tf.sigmoid(model.logits)), feed_dict = feed)\n",
    "    rouge_ = calculate_rouge(predicted, batch_y, cp_batch_clss, batch_x)\n",
    "    rouges.append(rouge_)\n",
    "    pbar.set_postfix(rouge = rouge_)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 19,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "0.26330408"
      ]
     },
     "execution_count": 19,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "np.mean(rouges)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.6.8"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
